import {
  defineComponent,
  ref,
} from 'vue'

import {
  ElButton,
  ElCol,
  ElMessage,
  ElRow,
} from 'element-plus'

import { createForm, onFormInit } from '@formily/core'

import { useRoute } from 'vue-router'

import type { ComprehensiveScore } from '@/types/scholarship'
import { useDict } from '@/utils/dict'
import {
  addComprehensiveScore,
  editComprehensiveScore,
  getComprehensiveScoreListById,
} from '@/api/scholarship'
import useUserStore from '@/store/modules/user'
import ComprehensiveForm from '@/views/scholarship/comprehensiveScore/components/ComprehensiveForm'
import DictTag from '@/components/DictTag/index.vue'

export default defineComponent({
  setup() {
    const currentUser = useUserStore()
    const route = useRoute()
    const id = route.query.id as string
    const { sys_yes_no, ...dicts } = useDict('deyu', 'zhiyu', 'laoyu', 'shenyu', 'nengyu', 'sys_yes_no')
    const dictMap = [
      ['德育', 'deyu', 'deTotal'],
      ['智育', 'zhiyu', 'zhiTotal'],
      ['劳育', 'laoyu', 'laoTotal'],
      ['身育', 'shenyu', 'shenTotal'],
      ['能育', 'nengyu', 'nengTotal'],
    ] as const
    const isSelf = ref(true)
    const state = ref<{ isPass?: string; reason?: string }>({ isPass: '', reason: '' })

    const form = createForm<ComprehensiveScore>({
      effects() {
        onFormInit(async (form1) => {
          if (id) {
            const { data } = await getComprehensiveScoreListById(id)
            dictMap.forEach(([_, dictKey, fieldKey]) => {
              data[fieldKey] = dicts[dictKey].value
                .map(item => item.value)
                .filter((key) => {
                  const tmp = data[key as 'deHelp']
                  delete data[key as 'deHelp']
                  return tmp
                }) as unknown as string
            })
            isSelf.value = currentUser.name === data.studentCode
            form1.setValues(data, 'overwrite')
            form1.setFormState((state) => {
              state.editable = isSelf.value
            })
            state.value.isPass = data.isPass
            state.value.reason = data.reason
          }
        })
      },
    })

    const submit = () => {
      void form.submit(async (values) => {
        values.totalScore = '0'
        dictMap.forEach(([_, dictKey, fieldKey]) => {
          const total = dicts[dictKey].value
            .filter(item => (values[fieldKey] as unknown as string[])?.includes(item.value))
            .reduce((pre, cur) => {
              const score = Number.parseFloat(cur.remark || '0')
              values[cur.value as 'deHelp'] = score.toString()
              return pre + score
            }, 0)
          values.totalScore = (Number.parseFloat(values.totalScore || '0') + total).toString()
          values[fieldKey] = total.toString()
        })
        values.studentName = currentUser.nickName
        values.studentCode = currentUser.name
        values.sex = currentUser.sex
        values.deptId = currentUser.dept?.deptId.toString()
        if (id)
          await editComprehensiveScore(values)
        else
          await addComprehensiveScore(values)
        ElMessage.success('操作成功')
      })
    }

    return () => (
      <div class="p-2 md:p-4 h-full">
        <ElRow gutter={10} class="mb-4">
          <ElCol span={1.5}>
            {
              isSelf.value
                && (
                  <ElButton
                    type="primary"
                    plain
                    icon="Plus"
                    onClick={submit}
                  >
                    保存
                  </ElButton>
                )
            }
          </ElCol>
        </ElRow>
        <ElRow gutter={20} class="mb-4">
          <ElCol span={1.5} class="flex">
            <div class="flex">
              <span class="mr-2 font-bold text-gray-700">是否审核通过:</span>
              <DictTag value={state.value.isPass} options={sys_yes_no.value} type="tag" />
            </div>

          </ElCol>
          <ElCol span={1.5}>
            <span class="mr-2 font-bold text-gray-700">未通过原因:</span>
            <span>{state.value.reason}</span>
          </ElCol>
        </ElRow>
        <ComprehensiveForm form={form} />
      </div>
    )
  },
})
